let app = getApp()
let req = require('../../utils/request')
let firstTime = 0
let secondTime = 0
let time = 0
let times = 0
Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		previewPages: {
			type: Boolean,
			value: false,
		},
		detailContent: {
			type: Object,
			value: {},
		},
		Variable: {
			type: Number,
			value: 0,
		},
		clientHeights: {
			type: Number,
			value: 0,
		},
		opcityColors: {
			type: String,
			value: 'rgb(0,0,0,1)'
		},
		detailsTops: {
			type: Number,
			value: 20
		},
		topicInfoId: {
			type: String,
			value: '',
		},
		comment: {
			type: Array,
			value: []
		},
		clientWidth: {
			type: Number,
			value: 0
		},
		headers: {
			type: Array,
			value: []
		},
		commentMessage: {
			type: Boolean,
			value: true
		},
		//页面来源  0动态列表 1宠物 2类别 3互动通知
		previewFrom: {
			type: Number,
			value: 0
		},
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		// 预览页面所需
		vertical: false,
		autoplay: false,
		interval: 2000,
		duration: 500,
		current: 1,
		id: '',
		tops: 0,
		count: 0,
		commentContent: '',
		upMessageTime: true,
		messageImgs: [],
		userInfo: '',
		circleIds: '',
		//输入框弹起的高度
		inputHei: 0,
		focuseBlur: false,
		focuse: false,
		imgs: '',
		//回复评论id
		replyId: '',
		placeholder: '亲切的评论...',
		hidden: true,
		showLine: 2,
		notice: false,
		//点赞gif图显隐
		gifImg: false,
		//控制加号的显示
		addPush: false,
		loadBot: false,
		//发布话题变量是否显示dialog
		topicShow: true,
		topicsList: [],
		topTopicsList: [],
		videoCover: true,
		outCurrent: 1,
		showLoad: false,
		inputFlag: false,
		getEnvelope: -1,
		showCanvas: false,
		//控制持续点击红包特效
		continued: true,
		shareFriend: true,
		random: "?random=" + Math.ceil(Math.random() * 100),
		pagenum: 1
	},
	/**
	 * 组件的方法列表
	 */
	lifetimes: {
		attached: function () {
			// 在组件实例进入页面节点树时执行
			this.setData({
				userInfo: app.globalData.communities.userId,
				cId: app.globalData.cId,
				userAvatarUrl: wx.getStorageSync('userInfo')
			})
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
		},
	},
	methods: {
		conreq(topicinfoid, redid) {
			req.globalLoading(true)
			req.request('get', '/rms/pack/detail?topicInfoId=' + topicinfoid + '&redpacketId=' + redid).then(res => {
				console.log(res);
				this.setData({
					whoRed: res.data.rmsRedPacketInfo,
					continued: true
				})
				req.globalLoading(false)
				if (res.data.grabStatus == 1) {
					wx.navigateTo({
						url: '../../pages_sub/redEnvelopes/red?redpacketId=' + redid + '&topicInfoId=' + topicinfoid,
					})
				} else {
					if (res.data.redpacketStatus == 4) {
						//抢光
						this.setData({
							getEnvelope: 1,
							'detailContent.getRedpack': 1
						})
						this.triggerEvent("modifyState", {
							id: redid,
						})
					} else if (res.data.redpacketStatus == 3) {
						//过期
						this.setData({
							getEnvelope: 2,
							'detailContent.getRedpack': 1
						})
						this.triggerEvent("modifyState", {
							id: redid,
						})
					} else {
						//正常
						this.setData({
							getEnvelope: 0
						})
					}
				}
			})
		},
		//获取随机值
		getRandomInt(min, max) {
			min = Math.ceil(min);
			max = Math.floor(max);
			return Math.floor(Math.random() * (max - min)) + min; //不含最大值，含最小值
		},
		//单击事件
		praiseClick(e) {
			//随机时间取值
			if (this.data.continued) {
				this.setData({
					continued: false
				})
				times = this.getRandomInt(1000, 1500)
			}
			if (secondTime == 0) {
				secondTime = e.timeStamp
				firstTime = e.timeStamp
			} else {
				if (e.timeStamp - secondTime < 300) {
					secondTime = e.timeStamp
					if (e.timeStamp - firstTime > times) {
						secondTime = 0
						this.conreq(e.currentTarget.dataset.topicinfoid, e.currentTarget.dataset.redid)
					}
				} else {
					secondTime = 0
				}
			}
			wx.vibrateShort({
				type: 'heavy'
			});
			this.setData({
				count: this.data.count + 1,
				showCanvas: true
			});
			clearTimeout(time)
			time = setTimeout(() => {
				this.setData({
					showCanvas: false,
					count: 0
				})
			}, 430)
		},
		lookDetail(e) {
			this.setData({
				getEnvelope: -1
			})
			wx.navigateTo({
				url: '../../pages_sub/redEnvelopes/red?redpacketId=' + e.currentTarget.dataset.redid + '&topicInfoId=' + e.currentTarget
					.dataset.topicinfoid,
			})
		},
		//抢红包
		goRedbox(e) {
			req.globalLoading(true)
			req.request('get', '/rms/pack/get?topicInfoId=' + e.currentTarget.dataset.topicinfoid + '&redpackId=' + e.currentTarget
				.dataset.redid + '&communityId=' + app.globalData.cId).then(res => {
					req.globalLoading(false)
					this.setData({
						getEnvelope: -1,
						'detailContent.getRedpack': 1
					})
					this.triggerEvent("modifyState", {
						id: e.currentTarget.dataset.redid,
					})
					wx.navigateTo({
						url: '../../pages_sub/redEnvelopes/red?redpacketId=' + e.currentTarget.dataset.redid + '&topicInfoId=' + e.currentTarget
							.dataset.topicinfoid,
					})
				})
		},
		mask() {
			this.setData({
				getEnvelope: -1
			})
		},
		getRedBox(e) {
			this.setData({
				'detailContent.getRedpack': 1
			})
			req.globalLoading(true)
			req.request('get', '/rms/pack/detail?topicInfoId=' + e.currentTarget.dataset.topicinfoid + '&redpacketId=' + e.currentTarget
				.dataset.redid).then(res => {
					this.setData({
						whoRed: res.data.rmsRedPacketInfo
					})
					req.globalLoading(false)
					if (res.data.grabStatus == 1) {
						wx.navigateTo({
							url: '../../pages_sub/redEnvelopes/red?redpacketId=' + e.currentTarget.dataset.redid + '&topicInfoId=' + e.currentTarget
								.dataset.topicinfoid,
						})
					} else {
						if (res.data.redpacketStatus == 4) {
							//抢光
							this.setData({
								getEnvelope: 1
							})
						} else if (res.data.redpacketStatus == 3) {
							//过期
							this.setData({
								getEnvelope: 2
							})
						} else {
							//正常
							this.setData({
								getEnvelope: 0
							})
						}
					}
				})
		},
		//item发生未知变化时
		tiggerTransition(e) {
			if (Math.abs(this.data.Variable - e.detail.dy) > 5) {
				this.setData({
					hidden: false
				})
			} else {
				this.setData({
					hidden: true
				})
			}
			let arr1 = Math.abs(this.data.Variable - e.detail.dy) / this.data.clientHeights
			let arr = 'rgba(0, 0, 0,' + (1 - arr1).toFixed(2) + ')'
			this.setData({
				opcityColors: arr
			})
		},
		//点击隐藏
		clickHidden() {
			let arr = !this.data.hidden
			this.setData({
				hidden: arr,
				Variable: 0
			})
		},
		finishAn(e) {
			this.setData({
				Variable: 0
			})
			if (e.detail.current != 1) {
				this.setData({
					previewPages: false,
					outCurrent: 1,
					hidden: true,
					current: 1
				})
			}
		},
		//触发滑动时候的事件
		triggerSlide(e) {
			console.log(e);
			this.setData({
				outCurrent: e.detail.current
			})
		},
		redClick() {
			let arr = !this.data.notice
			this.setData({
				notice: arr,
				focuse: true
			})
		},
		allshow() {
			let that = this
			const query = wx.createSelectorQuery().in(that); //创建对象
			query.select('.showContent').boundingClientRect(function (rect) {
				console.log(rect.height);
				if (rect.height >= 40) {
					if (that.data.showLine) {
						that.setData({
							showLine: 0
						})
					} else {
						that.setData({
							showLine: 2
						})
					}
				}
			}).exec();
		},
		longtap() {
			let that = this
			wx.showModal({
				title: '提示',
				content: '确定要删除该留言吗？',
				success(res) {
					if (res.confirm) {
						that.setData({
							imgs: []
						})
					}
				}
			})
		},
		chooseImg() {
			wx.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log(res);
					res.tempFilePaths.forEach(item => {
						this.uploads(item)
					})
				}
			})
		},
		uploads(item) {
			let that = this
			wx.uploadFile({
				url: app.globalData.reqUrl + "/oss/upload",
				filePath: item,
				name: 'file',
				header: {
					"Content-Type": "multipart/form-data",
					Authorization: 'Bearer ' + wx.getStorageSync('token')
				},
				formData: {
					ossType: 'TAIN'
				},
				success: function (res) {
					let data = JSON.parse(res.data)
					let arrs;
					arrs = `https://${data.data}`
					that.setData({
						imgs: arrs,
						focuse: true
					})
				},
			})
		},
		focusd() {
			this.setData({
				focuse: true
			})
		},
		pushMess() {
			this.triggerEvent('pushMess')
			if (this.data.commentContent == '') {
				wx.showToast({
					title: '请填写内容',
					icon: 'none',
					duration: 500
				})
				return false
			}
			let that = this
			this.setData({
				showLoad: true
			})
			if (this.data.replyId != '') {
				req.postData(`/comment/tms/add`, {
					topicInfoId: this.data.topicInfoId,
					img: this.data.imgs,
					content: this.data.commentContent,
					replyCommentId: this.data.replyId,
					isSend: this.data.notice,
					type: 1
				}, function (res) {
					wx.showToast({
						icon: 'none',
						title: res.message,
					})
					if (res.code === 200) {
						that.getComment()
						let arr = 'detailContent.commentNum'
						that.setData({
							commentContent: '',
							inputHei: 400,
							focuseBlur: false,
							imgs: '',
							[arr]: that.data.detailContent.commentNum * 1 + 1,
							replyId: '',
							notice: false,
							commentMessage: false,
							focuse: false,
							showLoad: false
						})
					}
				})
			} else {
				req.postData(`/comment/tms/add`, {
					topicInfoId: this.data.topicInfoId,
					img: this.data.imgs,
					content: this.data.commentContent,
					replyCommentId: this.data.replyId,
					isSend: this.data.notice,
					type: 1
				}, function (res) {
					wx.showToast({
						icon: 'none',
						title: res.message,
					})
					if (res.code === 200) {
						that.getComment()
						let arr = 'detailContent.commentNum'
						that.setData({
							commentContent: '',
							inputHei: 400,
							focuseBlur: false,
							imgs: '',
							[arr]: that.data.detailContent.commentNum * 1 + 1,
							notice: false,
							commentMessage: false,
							focuse: false,
							showLoad: false
						})
					}
				})
			}
		},
		blur() {
			this.setData({
				inputHei: 400,
				focuse: false,
				focuseBlur: false,
				replyId: '',
				imgs: '',
				commentContent: ''
			})
		},
		focuse() {
			if (!this.data.inputFlag) {
				this.setData({
					inputHei: app.globalData.keyboardHeight + 400
				})
			}
			if (this.data.replyId != '') {
				this.setData({
					focuseBlur: true,
					focuse: true
				})
			} else {
				this.setData({
					focuseBlur: true,
					focuse: true,
					placeholder: '亲切的评论...'
				})
			}
		},
		focus(e) {
			wx.onKeyboardHeightChange(res => { //监听键盘高度变化
				if (this.data.inputFlag) {
					this.setData({
						inputHei: res.height + 400
					})
				} else {
					if (app.globalData.keyboardHeight) {
						this.setData({
							inputHei: app.globalData.keyboardHeight + 400,
							inputFlag: true
						})
					} else {
						this.setData({
							inputHei: e.detail.height + 400,
							inputFlag: true
						})
						app.globalData.keyboardHeight = e.detail.height
					}
				}
				app.globalData.keyboardHeight = res.height
			})
		},
		reqDetail() {
			req.request('get', '/tms/info/details', {
				topicInfoId: this.data.topicInfoId
			}).then(res => {
				console.log(res);
				let arr = []
				res.data.tmsTopicPraiseRecords.forEach(item => {
					arr.push({
						img: item.memberIcon,
						nameText: item.memberName
					})
				})
				this.setData({
					headers: arr
				})
			})
		},
		deleteMessage(e) {
			let that = this
			wx.showModal({
				title: '提示',
				content: '确定要删除该留言吗？',
				success(res) {
					if (res.confirm) {
						req.getData('/comment/tms/delete', {
							commentId: e.currentTarget.dataset.id
						}, function (res) {
							if (res.code === 200) {
								wx.showToast({
									title: '删除成功',
									duration: 300
								})
								let arr = 'detailContent.commentNum'
								that.setData({
									[arr]: that.data.detailContent.commentNum * 1 - 1
								})
								that.getComment()
								that.triggerEvent('deleteMessage')
							} else {
								wx.showToast({
									title: res.message,
									icon: 'none',
									duration: 1000
								})
							}
						})
					}
				}
			})

		},
		closeMessage() {
			this.setData({
				messageShow: false
			})
		},
		getMessage(e) {
			let that = this
			that.setData({
				message: e.detail.value
			})
		},
		upMessage() {
			let that = this
			if (that.data.upMessageTime === false) {
				wx.showToast({
					title: '留言需间隔2秒',
					icon: 'none'
				})
				return
			}
			that.setData({
				upMessageTime: false,
			})
			setTimeout(function () {
				that.setData({
					upMessageTime: true,
				})
			}, 2000)
			for (let i = 0; i < that.data.messageImgs.length; i++) {
				if (i == that.data.messageImgs.length - 1) {
					messageImg += that.data.messageImgs[i]
				} else {
					messageImg += (that.data.messageImgs[i] + ',')
				}
			}
			let obj = {
				content: that.data.message,
				cId: app.globalData.cId,
				circleId: this.data.circleIds,
				observer: app.globalData.communities.userId,
				status: '1',
			};
			req.request('post', '/community/circle/comments', obj).then(res => {
				this.setData({
					messageShow: false
				})
			})
		},
		showMessage(e) {
			this.setData({
				replyId: e.currentTarget.dataset.id,
				placeholder: '@' + e.currentTarget.dataset.name
			})
			this.focuse()
		},
		commentMes(e) {
			this.setData({
				commentContent: e.detail.value
			})
		},
		//显示弹框留言
		showComment() {
			this.setData({
				commentMessage: false
			})
		},
		//关闭留言弹框
		maskNoteClick() {
			this.setData({
				commentMessage: true,
				shareFriend: true
			})
		},
		
		getComment() {
			let that = this
			req.getData('/comment/tms/list', {
				pageNum: this.data.pagenum,
				pageSize: 100,
				comboId: that.data.topicInfoId
			}, function (res) {
				
				if (res.data.list != null) {
					res.data.list.forEach((item, index) => {
						if (item.comments.length > 0) {
							item.comments.forEach((child, idx) => {
								if (child.img == undefined) {
									return false;
								}
								if (child.img.indexOf(',') > -1) {
									child.img = child.img.split(/[,_]/);
								} else {
									child.img = [child.img]
								}
							})
						}
						if (item.img == undefined) {
							item.img = ''
						}
						if (item.img.indexOf(',') > -1) {
							item.img = item.img.split(/[,_]/);
						} else {
							item.img = [item.img]
						}
					})
				}
				that.setData({
					comment: res.data.list
				})
			})
		},
		showPicView(e) {
			let img = e.currentTarget.dataset.src
			wx.previewImage({
				urls: img,
			})
		},
		//详情点赞
		clickGoods(e) {
			this.triggerEvent("clickGoods", {
				id: e.currentTarget.dataset.id,
				praise: e.currentTarget.dataset.praise
			})
			let that = this
			let praise = e.currentTarget.dataset.praise;
			let item = 'detailContent.praise';
			let likesNum = 'detailContent.likesNum';
			let lkm = parseInt(that.data.detailContent.likesNum);
			if (praise == true) {
				that.setData({
					[item]: 0,
					[likesNum]: lkm - 1,
				})
			} else {
				that.setData({
					[item]: 1,
					[likesNum]: lkm + 1,
				})
			}
			// this.reqDetail()
		},
		insideTransition() {
			this.setData({
				Variable: 0
			})
		},
		//滑动详情数量的计算
		change(e) {
			this.setData({
				current: e.detail.current + 1
			})
		},
		//关闭详情清空数据
		cancle() {
			this.setData({
				previewPages: false,
				detailContent: {},
				current: 1
			})
		},
		//请求留言
		topTopicsList() {
			req.request('get', '/tms/topic/list').then(res => {
				this.setData({
					topicsList: res.data.topics,
					topTopicsList: res.data.topTopics
				})
			})
		},
		goUserInfo(e) {
			let item = e.currentTarget.dataset.item

			let previewFrom = this.data.previewFrom
			let url = ''
			if (previewFrom == 1 || previewFrom == 3) {
				url = '../../../pages_sub/userInfo/index?peoId='
			} else {
				url = '../../pages_sub/userInfo/index?peoId='
			}
			wx.navigateTo({
				url: url + item.memberId
			})
		},
		goUserInfoComm(e) {
			let item = e.currentTarget.dataset.item
			let previewFrom = this.data.previewFrom
			let url = ''
			if (previewFrom == 0) {
				url = '../../pages_sub/userInfo/index?peoId='
			} else if (previewFrom == 1) {
				url = '../../../pages_sub/userInfo/index?peoId='
			} else if (previewFrom == 2) {
				url = '../../pages_sub/userInfo/index?peoId='
			} else if (previewFrom == 3) {
				url = '../../../pages_sub/userInfo/index?peoId='
			}
			wx.navigateTo({
				url: url + item.memberId
			})
		}

	}
})
